﻿namespace IS.Projecto.ImportarCSVToXml
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Xml;
    using System.Xml.Schema;
    using System.Xml.Serialization;
    using ImportarCSV;

    internal class Program
    {
        private string _dataPath = "";
        private string _xmlPath = "";
        private bool _waitForKey;

        private static void Main(string[] args)
        {
            var instance = new Program();
            instance.Run(args);
        }

        private void Run(string[] args)
        {
            //Inicializa os argumentos necessários
            foreach (string s in args)
            {
                string[] pair = s.Split('=');
                if (pair.Length == 2 && pair[0].ToLower().Equals("csvpath"))
                {
                    _dataPath = Path.GetFullPath(pair[1]);
                }
                else if (pair.Length == 2 && pair[0].ToLower().Equals("xmlpath"))
                {
                    _xmlPath = Path.GetFullPath(pair[1]);
                }
                else if (s.ToLower().Equals("/w"))
                    _waitForKey = true;
            }

            //Importar dados de csv
            var importer = new CsvDirectoryImporter(_dataPath);
            importer.Import();

            Console.WriteLine("A serializar dados...");
            Console.WriteLine("A serializar Docentes...");
            SerializeList(importer.ListaDocentes, "Docentes", string.Format("{0}\\Docentes.xml", _xmlPath));
            Console.WriteLine("A serializar Salas...");
            SerializeList(importer.ListaSalas, "Salas", string.Format("{0}\\Salas.xml", _xmlPath));
            Console.WriteLine("A serializar Horarios...");
            SerializeList(importer.ListaHorarios, "Horarios", string.Format("{0}\\Horarios.xml", _xmlPath));
            Console.WriteLine("A serializar Inscricoes...");
            SerializeList(importer.ListaInscricoes, "Inscricoes", string.Format("{0}\\Inscricoes.xml", _xmlPath));
            Console.WriteLine("A serializar Unidades curriculares...");
            SerializeList(importer.ListaUCs, "UnidadesCurriculares", string.Format("{0}\\UnidadesCurriculares.xml", _xmlPath));

            Console.WriteLine("A validar Xml...");
            Console.WriteLine("A validar Horarios...");
            ValidateSchema(string.Format("{0}\\Horarios.xml", _xmlPath), string.Format("{0}\\DataSchema.xsd", _xmlPath));
            Console.WriteLine("A validar Docentes...");
            ValidateSchema(string.Format("{0}\\Docentes.xml", _xmlPath), string.Format("{0}\\DataSchema.xsd", _xmlPath));
            Console.WriteLine("A validar Inscricoes...");
            ValidateSchema(string.Format("{0}\\Inscricoes.xml", _xmlPath), string.Format("{0}\\DataSchema.xsd", _xmlPath));
            Console.WriteLine("A validar Salas...");
            ValidateSchema(string.Format("{0}\\Salas.xml", _xmlPath), string.Format("{0}\\DataSchema.xsd", _xmlPath));
            Console.WriteLine("A validar Unidades Curriculares...");
            ValidateSchema(string.Format("{0}\\UnidadesCurriculares.xml", _xmlPath), string.Format("{0}\\DataSchema.xsd", _xmlPath));
            Console.WriteLine("Concluido");

            if (_waitForKey)
            {
                Console.WriteLine("Press any key...");
                Console.ReadKey();
            }
        }

        private void SerializeList<T>(IList<T> list, string rootName, string filename)
        {
            Stream filestream = null;
            try
            {

                var root = new XmlRootAttribute(rootName)
                               {
                                   Namespace = "http://xml.is.estg.org/schema/DataSchema"
                               };
                var serializer = new XmlSerializer(list.GetType(), root);
                filestream = new FileStream(filename, FileMode.Create);
                var writer = new StreamWriter(filestream);

                serializer.Serialize(writer, list);
            }
            finally
            {
                if (filestream != null)
                    filestream.Close();
            }
        }

        private void ValidateSchema(string file, string schema)
        {
            // Create the XmlSchemaSet class.
            var schemaSet = new XmlSchemaSet();

            if (!File.Exists(schema))
            {
                File.Copy(Path.GetFileName(schema), schema);
            }

            // Add the schema to the collection.
            schemaSet.Add("http://xml.is.estg.org/schema/DataSchema", schema);

            // Set the validation settings.
            var settings = new XmlReaderSettings
                               {
                                   ValidationType = ValidationType.Schema,
                                   Schemas = schemaSet,
                                   ValidationFlags = XmlSchemaValidationFlags.ProcessInlineSchema |
                                                     XmlSchemaValidationFlags.ReportValidationWarnings |
                                                     XmlSchemaValidationFlags.ProcessIdentityConstraints |
                                                     XmlSchemaValidationFlags.ProcessSchemaLocation
                               };
            settings.ValidationEventHandler += ValidationCallBack;

            // Create the XmlReader object.
            var reader = XmlReader.Create(file, settings);

            // Parse the file. 
            while (reader.Read())
            {}
            reader.Close();
        }

        // Display any validation errors.
        private void ValidationCallBack(object sender, ValidationEventArgs e)
        {
            Console.WriteLine("Validation Error: {0}", e.Message);
        }

    }
}